

let http = require('http');
let fs= require('fs');
let querystring = require("querystring");

let number=0;

function getContent(par) {
	// 	{
	// 	'bookid':'794',
	// 	"id":"352",
	// 	"gid":"0",
	// 	"pid":"0"
	// }
	// 
	// 

	let promis = new Promise(function (resolve, reject) {

		let params = querystring.stringify(par);
		const header = {
			"Accept": "*/*",
			"Accept-Encoding": "gzip, deflate",
			"Accept-Language": "zh-CN,zh;q=0.8",
			"Connection": "keep-alive",
			"Content-Length": params.length,
			"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			"Cookie": "PHPSESSID=jnr7pu0t6vk3pbsutonbmu6346; acw_tc=AQAAAEOA7V36JgkA3OqYPVauuRXPnrUi; qs_readFgorid=rdlp1483000817_6193_7704_4398_38; qs_isreadlist=1448%2C794; qs_resUrl=http://www.qiaobooks.com/read/794; qs_c_read_mode=1; qs_ssid=258d266f33626b938d26ebb7a57e9aa9; qs_exp=700; Hm_lvt_292c6ee5999422a9816ba331d505c0e3=1490838915,1490926285,1491012118,1491357978; Hm_lpvt_292c6ee5999422a9816ba331d505c0e3=1491372152",
			"Host": "www.qiaobooks.com",
			"Origin": "http://www.qiaobooks.com",
			"Referer": "http://www.qiaobooks.com/read/794",
			"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1",
			"X-Requested-With": "XMLHttpRequest",
		};
		const option = {
			hostname: 'www.qiaobooks.com',
			port: '80',
			path: '/Readdoc/getContent',
			method: 'post',
			headers: header
		};
		let req = http.request(option, function (res) {
			console.log(res.statusCode+" 次数："+(++number));
			let content = '';
			res.on('data', function (chunk) {
				let str = chunk.toString();
				content += str;
			});
			res.on('end', function () {
				try {
					content = JSON.parse(content);
					resolve(content);
				} catch (e) {
					console.log(e.message);
					fs.readFile('./json/error.log', 'utf-8', function (err, data) {
						if (err) throw Error('读取content失败');
						fs.writeFile('./json/error.log', data + par.bookid + ' 信息获取失败\n', function (err) {
							if (err) console.log(err);
						})
					})

				}
			})
		});

		req.on('error', function (e) {
			console.log(e.message)
		});
		req.write(params);

		req.end();
	});

	return promis;

}

module.exports.getContent = getContent;